# -*- coding:utf-8 -*-
from ElevatorAdmin.settings import IS_WX_CITY_CENTER, redis_host, redis_password, RLHOST, RL_AGING_TIME
import redis
from manufacturer.models import User, ElevatorStatus, AuthorityCode
from users.models import SystemLog
import requests
import time
import json
import datetime
from celery import shared_task


r = redis.Redis(host=redis_host, port=6379, db=4, password=redis_password)

"""
redis 数据结构 hash
浪潮使用单通道 key: rlLiftStatus, field: '0', value: register_code 浪潮只会使用这个
单梯多梯 key: rlLiftStatus, field: '1', value: register_code 
单梯多梯 key: rlLiftStatus, field: '2', value: register_code 使用两个通道 
"""

code_list = []


@shared_task
def handler_multi_monitor_for_status(register_codes, ses, username):
    for register_code in register_codes:
        handler_monitor_for_status(register_code, ses, username)


@shared_task()
def handler_single_monitor_for_status(register_code, ses, username):
    handler_monitor_for_status(register_code, ses, username)


def handler_monitor_for_status(register_code, ses, username):
    """ 单梯 多梯 调用 """

    print u"handler_monitor_for_status 单梯开始执行了"

    if not register_code:
        print "111111111"
        return

    if register_code in code_list:
        print "0000000000"
        return

    code_map = r.hgetall("rlLiftStatus")
    # 存在 表示处于监控中 返回
    if register_code in code_map.values():
        print "222222222222"
        return

    # 如果双通道都处于监控状态
    if code_map.get("1", None) and code_map.get("1", None) != "0" and code_map.get("2", None) and code_map.get("2", None) != "0":
        print "3333333333"
        return

    # 如果两个通道 优先1
    if not code_map.get("1", None) or code_map.get("1", None) == "0":
        k = "1"
    else:  # not code_map.get("2", None) or code_map.get("1", None) == "0":
        k = "2"
    if not code_list or register_code not in code_list:
        if len(code_list) >= 5:
            code_list.pop(0)
            code_list.append(register_code)
    es = ElevatorStatus.objects.filter_active(e=register_code).first()
    start = es.update_time if es else datetime.datetime(year=1970, month=1, day=1)
    # 单梯 多梯 使用 1 2
    r.hset("rlLiftStatus", k, register_code)
    # 1 监控 2 取消监控
    url_request = RLHOST + "1&regcode=" + register_code + "&ses=" + ses
    url_cancel = RLHOST + "2&regcode=" + register_code + "&ses=" + ses
    try:
        SystemLog.objects.create(create_by=username, log=url_request, log_type=2)
        res = requests.get(url_request)
        res = res.json()
        SystemLog.objects.create(create_by=username, log=json.dumps(res, ensure_ascii=False), log_type=2)
    except Exception as e:
        print e
        # 保持field 0的存在， 没有监控时设为0
        r.hset("rlLiftStatus", k, "0")
        SystemLog.objects.create(create_by=username, log=u"请求开启监控时，日立服务器崩了", log_type=2)
        print "444444444"
        return
    for i in range(RL_AGING_TIME):
        time.sleep(1)
        # TODO
        # continue
        es = ElevatorStatus.objects.filter_active(e=register_code).first()
        if es and es.update_time > start:
            try:
                SystemLog.objects.create(create_by=username, log=url_cancel, log_type=2)
                res = requests.get(url_cancel)
                res = res.json()
                SystemLog.objects.create(create_by=username, log=json.dumps(res, ensure_ascii=False), log_type=2)
                r.hset("rlLiftStatus", k, "0")
                print "555555555"
                return
            except Exception as e:
                print e
                r.hset("rlLiftStatus", k, "0")
                SystemLog.objects.create(create_by=username, log=u"请求关闭监控时，日立服务器崩了", log_type=2)
                print "66666666"
                return
    try:
        SystemLog.objects.create(create_by=username, log=url_cancel, log_type=2)
        res = requests.get(url_cancel)
        res = res.json()
        SystemLog.objects.create(create_by=username, log=json.dumps(res, ensure_ascii=False), log_type=2)
        r.hset("rlLiftStatus", k, "0")
        print "777777777"
        return
    except Exception as e:
        print e
        r.hset("rlLiftStatus", k, "0")
        SystemLog.objects.create(create_by=username, log=u"请求关闭监控时，日立服务器崩了", log_type=2)
        print "88888888"

    # for k in code_map:
    #     v = code_map[k]
    #     if int(v) + 360 < time.time():
    #         url_cancel = RLHOST + "2&regcode=" + k + "&ses=" + ses
    #         try:
    #             res = requests.get(url_cancel)
    #             SystemLog.objects.create(create_by=u"市民中心", log=url_cancel, log_type=2)
    #             res = res.json()
    #             SystemLog.objects.create(create_by=u"市民中心", log=json.dumps(res, ensure_ascii=False), log_type=2)
    #         except Exception, e:
    #             print e
    #             SystemLog.objects.create(create_by=u"市民中心", log=u"日立服务器崩了", log_type=2)
    # r.delete("rlLiftStatus")
    # code_list = codes.split(",")
    # for code in code_list:
    #     url_request = RLHOST + "1&regcode=" + code + "&ses=" + ses
    #     r.hset("rlLiftStatus", code, time.time())
    #     try:
    #         res = requests.get(url_request)
    #         SystemLog.objects.create(create_by=u"市民中心", log=url_request, log_type=2)
    #         res = res.json()
    #         SystemLog.objects.create(create_by=u"市民中心", log=json.dumps(res, ensure_ascii=False), log_type=2)
    #     except Exception, e:
    #         print e
    #         SystemLog.objects.create(create_by=u"市民中心", log=u"日立服务器崩了", log_type=2)


def handler_lc_request_for_status(register_code, ses):
    """ 浪潮 请求调用 """

    print u" 浪潮开始调用了接口了 "
    codes_map = r.hgetall("rlLiftStatus")

    # 如果有这个注册代码 表示处于监控中 返回 不做处理
    if register_code in codes_map.values():
        return

    # 第一个通道不为0 即是说有已经在监控某个电梯了
    if codes_map.get("0", None) and codes_map.get("0", None) != "0":
        return

    es = ElevatorStatus.objects.filter_active(e=register_code).first()
    start = es.update_time if es else datetime.datetime(year=1970, month=1, day=1)
    # 浪潮使用field 0
    r.hset("rlLiftStatus", "0", register_code)
    # 1 监控 2 取消监控
    url_request = RLHOST + "1&regcode=" + register_code + "&ses=" + ses
    url_cancel = RLHOST + "2&regcode=" + register_code + "&ses=" + ses
    try:
        SystemLog.objects.create(create_by=u"浪潮", log=url_request, log_type=2)
        res = requests.get(url_request)
        res = res.json()
        SystemLog.objects.create(create_by=u"浪潮", log=json.dumps(res, ensure_ascii=False), log_type=2)
    except Exception as e:
        print e
        # 保持field 0的存在， 没有监控时设为0
        r.hset("rlLiftStatus", "0", "0")
        SystemLog.objects.create(create_by=u"浪潮", log=u"请求开启监控时，日立服务器崩了", log_type=2)
        return
    for i in range(RL_AGING_TIME):
        time.sleep(1)
        es = ElevatorStatus.objects.filter_active(e=register_code).first()
        if es and es.update_time > start:
            try:
                SystemLog.objects.create(create_by=u"浪潮", log=url_cancel, log_type=2)
                res = requests.get(url_cancel)
                res = res.json()
                SystemLog.objects.create(create_by=u"浪潮", log=json.dumps(res, ensure_ascii=False), log_type=2)
                r.hset("rlLiftStatus", "0", "0")
                return
            except Exception as e:
                print e
                r.hset("rlLiftStatus", "0", "0")
                SystemLog.objects.create(create_by=u"浪潮", log=u"请求关闭监控时，日立服务器崩了", log_type=2)
                return
    r.hset("rlLiftStatus", "0", "0")


















































































